/*
 * @Author: jhw jiaxianshengye@gmail.com
 * @LastEditTime: 2025-07-31 11:48:13
 * @LastEditors: jhw
 * @Description: 文件描述
 */

import * as ExcelJS from 'exceljs'
self.onmessage = async (e) => {
  const { data, fileName, chunkSize = 1000 } = e.data
  try {
    // 初始化工作簿和工作表
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('Sheet1')

    // 添加表头
    const headers = Object.keys(data[0])
    worksheet.columns = headers.map((header) => ({
      header,
      key: header,
      width: 20,
    }))

    // 分批处理数据
    const totalRows = data.length
    let processedRows = 0

    while (processedRows < totalRows) {
      // 获取当前批次的数据
      const chunk = data.slice(processedRows, processedRows + chunkSize)
      processedRows += chunk.length

      // 将批次数据添加到工作表
      chunk.forEach((row) => {
        worksheet.addRow(row)
      })

      // 向主线程发送进度更新
      const progress = Math.round((processedRows / totalRows) * 100)
      self.postMessage({ status: 'progress', progress })
    }

    // 生成Excel并提取ArrayBuffer
    const buffer = await workbook.xlsx.writeBuffer()
    const arrayBuffer = buffer.buffer

    // 发送结果给主线程
    self.postMessage(
      {
        status: 'success',
        arrayBuffer,
        fileName,
      },
      [arrayBuffer],
    )
  } catch (error) {
    self.postMessage({
      status: 'error',
      error: error.message,
    })
  }
}
